<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="XV6：介绍及项目结构, python,machine learning,deep learning,html,css,c,c++,cpp,cmake,ros,linux,ubuntu">
    <meta name="description" content="本文介绍了XV6，并介绍了XV6项目结构">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>XV6：介绍及项目结构 | JackWang&#39;s Blog</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery-3.6.0.min.js"></script>

<meta name="generator" content="Hexo 5.4.2">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/css/prism-line-numbers.css" type="text/css"></head>



   <style>
    body{
       background-image: url(https://cdn.jsdelivr.net/gh/Tokisaki-Galaxy/res/site/medias/background.jpg);
       background-repeat:no-repeat;
       background-size: 100% 100%;
       background-attachment:fixed;
    }
</style>



<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">JackWang&#39;s Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-book-reader" style="zoom: 0.6;"></i>
      
      <span>博客</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/tags">
          
          <i class="fas fa-tags" style="margin-top: -20px; zoom: 0.6;"></i>
          
	  <span>按标签归类文章</span>
        </a>
      </li>
      
      <li>
        <a href="/categories">
          
          <i class="fas fa-bookmark" style="margin-top: -20px; zoom: 0.6;"></i>
          
	  <span>按目录归类文章</span>
        </a>
      </li>
      
      <li>
        <a href="/archives">
          
          <i class="fas fa-archive" style="margin-top: -20px; zoom: 0.6;"></i>
          
	  <span>按日期分类文章</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>



<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">JackWang&#39;s Blog</div>
        <div class="logo-desc">
            
            JackWang的个人博客
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-book-reader"></i>
			
			博客
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/tags " style="margin-left:75px">
				  
				   <i class="fa fas fa-tags" style="position: absolute;left:50px" ></i>
			      
                              <span>按标签归类文章</    span>

                  </a>
                </li>
              
                <li>

                  <a href="/categories " style="margin-left:75px">
				  
				   <i class="fa fas fa-bookmark" style="position: absolute;left:50px" ></i>
			      
                              <span>按目录归类文章</    span>

                  </a>
                </li>
              
                <li>

                  <a href="/archives " style="margin-left:75px">
				  
				   <i class="fa fas fa-archive" style="position: absolute;left:50px" ></i>
			      
                              <span>按日期分类文章</    span>

                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('抱歉，这篇文章并不想让所有人都看到，请输入授权密码观看')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20220928233603685.png')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">XV6：介绍及项目结构</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Operating-System/">
                                <span class="chip bg-color">Operating System</span>
                            </a>
                        
                            <a href="/tags/xv6/">
                                <span class="chip bg-color">xv6</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/xv6/" class="post-category">
                                xv6
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2022-10-22
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2023-06-01
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    3.8k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    18 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20220928233603685-20221022150622618.png" alt="XV6 (Unix Version 6) System"></p>
<h2 id="0-前言"><a href="#0-前言" class="headerlink" title="0.前言"></a>0.前言</h2><p>我之前说过我正在开发自己的操作系统<code>JackOS</code>，但是在开启页表之后就遇到了困难，所以为了后续能够更好的开发<code>JackOS</code>，这段时间就去学习了一下<code>XV6</code>操作系统。</p>
<p>毕竟实践出真知，因此后面的安排就是准备魔改一下<code>xv6</code>系统，即在<code>xv6</code>的代码的基础上魔改其功能，例如增加系统调用、修改Shell、修改<code>Scheduler</code>等等。</p>
<p>因此，在开始这些项目之前，先写一篇文章来介绍<code>XV6</code>系统</p>
<h2 id="1-XV6介绍"><a href="#1-XV6介绍" class="headerlink" title="1. XV6介绍"></a>1. XV6介绍</h2><h3 id="A-Unix"><a href="#A-Unix" class="headerlink" title="A. Unix"></a>A. Unix</h3><p><code>UNIX</code>（非复用信息和计算机服务，英语：<code>Uniplexed Information and Computing Service</code>，<code>UnICS</code>），一种多用户、多进程的计算机操作系统，源自于从20世纪70年代开始在美国AT&amp;T公司的贝尔实验室开发的AT&amp;T Unix。<code>Unix</code>是第一个广泛流行的操作系统（原先最早的操作系统，类似于<code>Multics</code>这类的并没有广泛使用的操作系统我们就不说了）。</p>
<p><code>Unix</code>的前身为1964年开始的<code>Multics</code>，1965年时，贝尔实验室加入一项由通用电气和麻省理工学院合作的计划；该计划要创建一套多用户、多任务、多层次（multi－user、multi－processor、multi－level）的<code>MULTICS</code>操作系统。贝尔实验室参与了这个操作系统的研发，但因为开发速度太慢，1969年贝尔实验室决定退出这个计划。贝尔实验室的工程师，肯·汤普逊和丹尼斯·里奇，在此时自行开发了<code>Unix</code>。</p>
<p>此后的10年，<code>Unix</code>在学术机构和大型企业中得到了广泛的应用，当时的<code>UNIX</code>拥有者<code>AT&amp;T</code>公司以低廉甚至免费的许可将<code>Unix</code>源码授权给学术机构做研究或教学之用，许多机构在此源码基础上加以扩展和改进，形成了所谓的“<code>Unix</code>变种”，这些变种反过来也促进了<code>Unix</code>的发展，其中最著名的变种之一是由加州大学伯克利分校开发的伯克利软件套件(<code>BSD</code>)产品。</p>
<p>后来<code>AT&amp;T</code>意识到了<code>Unix</code>的商业价值，不再将<code>Unix</code>源码授权给学术机构，并对之前的<code>Unix</code>及其变种声明了著作权权利。<code>BSD</code>在<code>Unix</code>的历史发展中具有相当大的影响力，被很多商业厂家采用，成为很多商用<code>Unix</code>的基础。其不断增大的影响力终于引起了<code>AT&amp;T</code>的关注，于是开始了一场持久的著作权官司，这场官司一直打到<code>AT&amp;T</code>将自己的<code>Unix</code>系统实验室卖掉，新接手的<code>Novell</code>采取了一种比较开明的做法，允许UC Berkeley分校自由发布自己的<code>Unix</code>变种，但是前提是必须将来自于<code>AT&amp;T</code>的代码完全删除，于是诞生了<code>4.4 BSD Lite</code>版，由于这个版本不存在法律问题，<code>4.4 BSD Lite</code>成为了现代Berkeley软件包的基础版本。尽管后来，非商业版的<code>Unix</code>系统又经过了很多演变，但其中有不少最终都是创建在<code>BSD</code>版本上（<code>Linux</code>、<code>Minix</code>等系统除外）。所以从这个角度上，<code>4.4 BSD</code>又是所有自由版本<code>Unix</code>的基础，它们和<code>System V</code>及<code>Linux</code>等共同构成Unix操作系统。</p>
<h3 id="B-Version-6-Unix-V6"><a href="#B-Version-6-Unix-V6" class="headerlink" title="B. Version 6 Unix (V6)"></a>B. Version 6 Unix (V6)</h3><p><code>UNIX第六版</code>（英语：<code>Version 6 Unix</code>，简称 <code>V6</code>），由贝尔实验室于1975年5月释出的<code>UNIX</code>操作系统，是第一个对外公开的<code>UNIX</code>版本，主要运行在<code>DEC PDP-11</code>系列的小型计算机（Minicomputer）家族。前身为<code>Version 5 Unix</code>，后继版本为1978年至1979年发布的<code>Version 7 Unix</code>，但是直到1985年为止，<code>Version 6 Unix</code> 仍然可以运行。</p>
<p><code>Version 5 Unix</code>这个版本，<code>AT&amp;T</code>公司只授权给学术机构使用。<code>Version 6 Unix</code>以$200美元授权给学校等学术机构，而非学术机构也可以以美金$20,000的价格获得授权以进行商业使用。</p>
<h3 id="C-XV6"><a href="#C-XV6" class="headerlink" title="C. XV6"></a>C. XV6</h3><p><strong><code>XV6</code>是在ANSI C中针对多处理器x86系统的Unix第六版的现代重新实现</strong>。它在麻省理工学院的操作系统工程（6.828）课程中用于教学目的。</p>
<p>与<code>Linux</code>或<code>BSD</code>注重实用性不同，<code>XV6</code>注重教学，因此其非常简单，足以在一个学期内讲完。尽管简单，但<code>XV6</code>中仍然包含<code>Unix</code>的重要概念和组织。由于<code>V6</code>是基于<code>PDP-11</code>硬件系统编写的，而由于<code>PDP-11</code>机器没有被广泛使用，并且由于最初的操作系统是用过时的pre-ANSI C编写的，所以<code>MIT 6.838</code>这门课程没有学习原始的<code>V6</code>代码</p>
<p>这门课的教师基于原始的<code>V6</code>的代码进行了改变，使得<code>V6</code>能够在现代的计算机上运行，而最终形成的修改版操作系统称为<code>XV6</code></p>
<h2 id="2-XV6项目结构：理解Makefile"><a href="#2-XV6项目结构：理解Makefile" class="headerlink" title="2. XV6项目结构：理解Makefile"></a>2. XV6项目结构：理解<code>Makefile</code></h2><p>上面我们介绍了<code>XV6</code>系统的历史，而<code>XV6</code>系统是用<code>Makefile</code>组织的，因此为了后续魔改<code>XV6</code>系统，我们首先需要明白<code>XV6</code>的组织结构。</p>
<p><code>XV6</code>的<code>Makefile</code>内容如下</p>
<pre class="line-numbers language-makefile"><code class="language-makefile">OBJS <span class="token operator">=</span> \
    bio.o\
    console.o\
    exec.o\
    file.o\
    fs.o\
    ide.o\
    ioapic.o\
    kalloc.o\
    kbd.o\
    lapic.o\
    log.o\
    main.o\
    mp.o\
    picirq.o\
    pipe.o\
    proc.o\
    sleeplock.o\
    spinlock.o\
    string.o\
    swtch.o\
    syscall.o\
    sysfile.o\
    sysproc.o\
    trapasm.o\
    trap.o\
    uart.o\
    vectors.o\
    vm.o\

<span class="token comment" spellcheck="true"># Cross-compiling (e.g., on Mac OS X)</span>
<span class="token comment" spellcheck="true"># TOOLPREFIX = i386-jos-elf</span>

<span class="token comment" spellcheck="true"># Using native tools (e.g., on X86 Linux)</span>
<span class="token comment" spellcheck="true">#TOOLPREFIX = </span>

<span class="token comment" spellcheck="true"># Try to infer the correct TOOLPREFIX if not set</span>
<span class="token keyword">ifndef</span> TOOLPREFIX
TOOLPREFIX <span class="token operator">:=</span> <span class="token variable">$</span><span class="token punctuation">(</span><span class="token keyword">shell</span> if i386-jos-elf-objdump -i 2>&amp;1 <span class="token operator">|</span> grep <span class="token string">'^elf32-i386$$'</span> >/dev/null 2>&amp;1<span class="token punctuation">;</span> \
    then echo <span class="token string">'i386-jos-elf-'</span><span class="token punctuation">;</span> \
    elif objdump -i 2>&amp;1 <span class="token operator">|</span> grep <span class="token string">'elf32-i386'</span> >/dev/null 2>&amp;1<span class="token punctuation">;</span> \
    then echo <span class="token string">''</span><span class="token punctuation">;</span> \
    <span class="token keyword">else</span> echo <span class="token string">"***"</span> 1>&amp;2<span class="token punctuation">;</span> \
    echo <span class="token string">"*** Error: Couldn't find an i386-*-elf version of GCC/binutils."</span> 1>&amp;2<span class="token punctuation">;</span> \
    echo <span class="token string">"*** Is the directory with i386-jos-elf-gcc in your PATH?"</span> 1>&amp;2<span class="token punctuation">;</span> \
    echo <span class="token string">"*** If your i386-*-elf toolchain is installed with a command"</span> 1>&amp;2<span class="token punctuation">;</span> \
    echo <span class="token string">"*** prefix other than 'i386-jos-elf-', set your TOOLPREFIX"</span> 1>&amp;2<span class="token punctuation">;</span> \
    echo <span class="token string">"*** environment variable to that prefix and run 'make' again."</span> 1>&amp;2<span class="token punctuation">;</span> \
    echo <span class="token string">"*** To turn off this error, run 'gmake TOOLPREFIX= ...'."</span> 1>&amp;2<span class="token punctuation">;</span> \
    echo <span class="token string">"***"</span> 1>&amp;2<span class="token punctuation">;</span> exit 1<span class="token punctuation">;</span> fi<span class="token punctuation">)</span>
<span class="token keyword">endif</span>

<span class="token comment" spellcheck="true"># If the makefile can't find QEMU, specify its path here</span>
<span class="token comment" spellcheck="true"># QEMU = qemu-system-i386</span>

<span class="token comment" spellcheck="true"># Try to infer the correct QEMU</span>
<span class="token keyword">ifndef</span> QEMU
QEMU <span class="token operator">=</span> <span class="token variable">$</span><span class="token punctuation">(</span><span class="token keyword">shell</span> if which qemu > /dev/null<span class="token punctuation">;</span> \
    then echo qemu<span class="token punctuation">;</span> exit<span class="token punctuation">;</span> \
    elif which qemu-system-i386 > /dev/null<span class="token punctuation">;</span> \
    then echo qemu-system-i386<span class="token punctuation">;</span> exit<span class="token punctuation">;</span> \
    elif which qemu-system-x86_64 > /dev/null<span class="token punctuation">;</span> \
    then echo qemu-system-x86_64<span class="token punctuation">;</span> exit<span class="token punctuation">;</span> \
    <span class="token keyword">else</span> \
    qemu<span class="token operator">=</span>/Applications/Q.app/Contents/MacOS/i386-softmmu.app/Contents/MacOS/i386-softmmu<span class="token punctuation">;</span> \
    if test -x <span class="token variable">$$qemu;</span> then echo <span class="token variable">$$qemu;</span> exit<span class="token punctuation">;</span> fi<span class="token punctuation">;</span> fi<span class="token punctuation">;</span> \
    echo <span class="token string">"***"</span> 1>&amp;2<span class="token punctuation">;</span> \
    echo <span class="token string">"*** Error: Couldn't find a working QEMU executable."</span> 1>&amp;2<span class="token punctuation">;</span> \
    echo <span class="token string">"*** Is the directory containing the qemu binary in your PATH"</span> 1>&amp;2<span class="token punctuation">;</span> \
    echo <span class="token string">"*** or have you tried setting the QEMU variable in Makefile?"</span> 1>&amp;2<span class="token punctuation">;</span> \
    echo <span class="token string">"***"</span> 1>&amp;2<span class="token punctuation">;</span> exit 1<span class="token punctuation">)</span>
<span class="token keyword">endif</span>

CC <span class="token operator">=</span> <span class="token variable">$</span><span class="token punctuation">(</span>TOOLPREFIX<span class="token punctuation">)</span>gcc
AS <span class="token operator">=</span> <span class="token variable">$</span><span class="token punctuation">(</span>TOOLPREFIX<span class="token punctuation">)</span>gas
LD <span class="token operator">=</span> <span class="token variable">$</span><span class="token punctuation">(</span>TOOLPREFIX<span class="token punctuation">)</span>ld
OBJCOPY <span class="token operator">=</span> <span class="token variable">$</span><span class="token punctuation">(</span>TOOLPREFIX<span class="token punctuation">)</span>objcopy
OBJDUMP <span class="token operator">=</span> <span class="token variable">$</span><span class="token punctuation">(</span>TOOLPREFIX<span class="token punctuation">)</span>objdump
CFLAGS <span class="token operator">=</span> -fno-pic -static -fno-builtin -fno-strict-aliasing -O2 -Wall -MD -ggdb -m32 -Werror -fno-omit-frame-pointer
CFLAGS <span class="token operator">+=</span> <span class="token variable">$</span><span class="token punctuation">(</span><span class="token keyword">shell</span> <span class="token variable">$</span><span class="token punctuation">(</span>CC<span class="token punctuation">)</span> -fno-stack-protector -E -x c /dev/null >/dev/null 2>&amp;1 &amp;&amp; echo -fno-stack-protector<span class="token punctuation">)</span>
ASFLAGS <span class="token operator">=</span> -m32 -gdwarf-2 -Wa,-divide
<span class="token comment" spellcheck="true"># FreeBSD ld wants ``elf_i386_fbsd''</span>
LDFLAGS <span class="token operator">+=</span> -m <span class="token variable">$</span><span class="token punctuation">(</span><span class="token keyword">shell</span> <span class="token variable">$</span><span class="token punctuation">(</span>LD<span class="token punctuation">)</span> -V <span class="token operator">|</span> grep elf_i386 2>/dev/null <span class="token operator">|</span> head -n 1<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># Disable PIE when possible (for Ubuntu 16.10 toolchain)</span>
<span class="token keyword">ifneq</span> <span class="token punctuation">(</span><span class="token variable">$</span><span class="token punctuation">(</span><span class="token keyword">shell</span> <span class="token variable">$</span><span class="token punctuation">(</span>CC<span class="token punctuation">)</span> -dumpspecs 2>/dev/null <span class="token operator">|</span> grep -e <span class="token string">'[^f]no-pie'</span><span class="token punctuation">)</span>,<span class="token punctuation">)</span>
CFLAGS <span class="token operator">+=</span> -fno-pie -no-pie
<span class="token keyword">endif</span>
<span class="token keyword">ifneq</span> <span class="token punctuation">(</span><span class="token variable">$</span><span class="token punctuation">(</span><span class="token keyword">shell</span> <span class="token variable">$</span><span class="token punctuation">(</span>CC<span class="token punctuation">)</span> -dumpspecs 2>/dev/null <span class="token operator">|</span> grep -e <span class="token string">'[^f]nopie'</span><span class="token punctuation">)</span>,<span class="token punctuation">)</span>
CFLAGS <span class="token operator">+=</span> -fno-pie -nopie
<span class="token keyword">endif</span>

<span class="token symbol">xv6.img</span><span class="token punctuation">:</span> bootblock kernel
    dd if<span class="token operator">=</span>/dev/zero of<span class="token operator">=</span>xv6.img count<span class="token operator">=</span>10000
    dd if<span class="token operator">=</span>bootblock of<span class="token operator">=</span>xv6.img conv<span class="token operator">=</span>notrunc
    dd if<span class="token operator">=</span>kernel of<span class="token operator">=</span>xv6.img seek<span class="token operator">=</span>1 conv<span class="token operator">=</span>notrunc

<span class="token symbol">xv6memfs.img</span><span class="token punctuation">:</span> bootblock kernelmemfs
    dd if<span class="token operator">=</span>/dev/zero of<span class="token operator">=</span>xv6memfs.img count<span class="token operator">=</span>10000
    dd if<span class="token operator">=</span>bootblock of<span class="token operator">=</span>xv6memfs.img conv<span class="token operator">=</span>notrunc
    dd if<span class="token operator">=</span>kernelmemfs of<span class="token operator">=</span>xv6memfs.img seek<span class="token operator">=</span>1 conv<span class="token operator">=</span>notrunc

<span class="token symbol">bootblock</span><span class="token punctuation">:</span> bootasm.S bootmain.c
    <span class="token variable">$</span><span class="token punctuation">(</span>CC<span class="token punctuation">)</span> <span class="token variable">$</span><span class="token punctuation">(</span>CFLAGS<span class="token punctuation">)</span> -fno-pic -O -nostdinc -I. -c bootmain.c
    <span class="token variable">$</span><span class="token punctuation">(</span>CC<span class="token punctuation">)</span> <span class="token variable">$</span><span class="token punctuation">(</span>CFLAGS<span class="token punctuation">)</span> -fno-pic -nostdinc -I. -c bootasm.S
    <span class="token variable">$</span><span class="token punctuation">(</span>LD<span class="token punctuation">)</span> <span class="token variable">$</span><span class="token punctuation">(</span>LDFLAGS<span class="token punctuation">)</span> -N -e start -Ttext 0x7C00 -o bootblock.o bootasm.o bootmain.o
    <span class="token variable">$</span><span class="token punctuation">(</span>OBJDUMP<span class="token punctuation">)</span> -S bootblock.o > bootblock.asm
    <span class="token variable">$</span><span class="token punctuation">(</span>OBJCOPY<span class="token punctuation">)</span> -S -O binary -j .text bootblock.o bootblock
    ./sign.pl bootblock

<span class="token symbol">entryother</span><span class="token punctuation">:</span> entryother.S
    <span class="token variable">$</span><span class="token punctuation">(</span>CC<span class="token punctuation">)</span> <span class="token variable">$</span><span class="token punctuation">(</span>CFLAGS<span class="token punctuation">)</span> -fno-pic -nostdinc -I. -c entryother.S
    <span class="token variable">$</span><span class="token punctuation">(</span>LD<span class="token punctuation">)</span> <span class="token variable">$</span><span class="token punctuation">(</span>LDFLAGS<span class="token punctuation">)</span> -N -e start -Ttext 0x7000 -o bootblockother.o entryother.o
    <span class="token variable">$</span><span class="token punctuation">(</span>OBJCOPY<span class="token punctuation">)</span> -S -O binary -j .text bootblockother.o entryother
    <span class="token variable">$</span><span class="token punctuation">(</span>OBJDUMP<span class="token punctuation">)</span> -S bootblockother.o > entryother.asm

<span class="token symbol">initcode</span><span class="token punctuation">:</span> initcode.S
    <span class="token variable">$</span><span class="token punctuation">(</span>CC<span class="token punctuation">)</span> <span class="token variable">$</span><span class="token punctuation">(</span>CFLAGS<span class="token punctuation">)</span> -nostdinc -I. -c initcode.S
    <span class="token variable">$</span><span class="token punctuation">(</span>LD<span class="token punctuation">)</span> <span class="token variable">$</span><span class="token punctuation">(</span>LDFLAGS<span class="token punctuation">)</span> -N -e start -Ttext 0 -o initcode.out initcode.o
    <span class="token variable">$</span><span class="token punctuation">(</span>OBJCOPY<span class="token punctuation">)</span> -S -O binary initcode.out initcode
    <span class="token variable">$</span><span class="token punctuation">(</span>OBJDUMP<span class="token punctuation">)</span> -S initcode.o > initcode.asm

<span class="token symbol">kernel</span><span class="token punctuation">:</span> <span class="token variable">$</span><span class="token punctuation">(</span>OBJS<span class="token punctuation">)</span> entry.o entryother initcode kernel.ld
    <span class="token variable">$</span><span class="token punctuation">(</span>LD<span class="token punctuation">)</span> <span class="token variable">$</span><span class="token punctuation">(</span>LDFLAGS<span class="token punctuation">)</span> -T kernel.ld -o kernel entry.o <span class="token variable">$</span><span class="token punctuation">(</span>OBJS<span class="token punctuation">)</span> -b binary initcode entryother
    <span class="token variable">$</span><span class="token punctuation">(</span>OBJDUMP<span class="token punctuation">)</span> -S kernel > kernel.asm
    <span class="token variable">$</span><span class="token punctuation">(</span>OBJDUMP<span class="token punctuation">)</span> -t kernel <span class="token operator">|</span> sed <span class="token string">'1,/SYMBOL TABLE/d; s/ .* / /; /^$$/d'</span> > kernel.sym

<span class="token comment" spellcheck="true"># kernelmemfs is a copy of kernel that maintains the</span>
<span class="token comment" spellcheck="true"># disk image in memory instead of writing to a disk.</span>
<span class="token comment" spellcheck="true"># This is not so useful for testing persistent storage or</span>
<span class="token comment" spellcheck="true"># exploring disk buffering implementations, but it is</span>
<span class="token comment" spellcheck="true"># great for testing the kernel on real hardware without</span>
<span class="token comment" spellcheck="true"># needing a scratch disk.</span>
MEMFSOBJS <span class="token operator">=</span> <span class="token variable">$</span><span class="token punctuation">(</span><span class="token keyword">filter-out</span> ide.o,<span class="token variable">$</span><span class="token punctuation">(</span>OBJS<span class="token punctuation">)</span><span class="token punctuation">)</span> memide.o
<span class="token symbol">kernelmemfs</span><span class="token punctuation">:</span> <span class="token variable">$</span><span class="token punctuation">(</span>MEMFSOBJS<span class="token punctuation">)</span> entry.o entryother initcode kernel.ld fs.img
    <span class="token variable">$</span><span class="token punctuation">(</span>LD<span class="token punctuation">)</span> <span class="token variable">$</span><span class="token punctuation">(</span>LDFLAGS<span class="token punctuation">)</span> -T kernel.ld -o kernelmemfs entry.o  <span class="token variable">$</span><span class="token punctuation">(</span>MEMFSOBJS<span class="token punctuation">)</span> -b binary initcode entryother fs.img
    <span class="token variable">$</span><span class="token punctuation">(</span>OBJDUMP<span class="token punctuation">)</span> -S kernelmemfs > kernelmemfs.asm
    <span class="token variable">$</span><span class="token punctuation">(</span>OBJDUMP<span class="token punctuation">)</span> -t kernelmemfs <span class="token operator">|</span> sed <span class="token string">'1,/SYMBOL TABLE/d; s/ .* / /; /^$$/d'</span> > kernelmemfs.sym

<span class="token symbol">tags</span><span class="token punctuation">:</span> <span class="token variable">$</span><span class="token punctuation">(</span>OBJS<span class="token punctuation">)</span> entryother.S _init
    etags *.S *.c

<span class="token symbol">vectors.S</span><span class="token punctuation">:</span> vectors.pl
    ./vectors.pl > vectors.S

ULIB <span class="token operator">=</span> ulib.o usys.o printf.o umalloc.o

<span class="token symbol">_%</span><span class="token punctuation">:</span> %.o <span class="token variable">$</span><span class="token punctuation">(</span>ULIB<span class="token punctuation">)</span>
    <span class="token variable">$</span><span class="token punctuation">(</span>LD<span class="token punctuation">)</span> <span class="token variable">$</span><span class="token punctuation">(</span>LDFLAGS<span class="token punctuation">)</span> -N -e main -Ttext 0 -o <span class="token variable">$@</span> <span class="token variable">$^</span>
    <span class="token variable">$</span><span class="token punctuation">(</span>OBJDUMP<span class="token punctuation">)</span> -S <span class="token variable">$@</span> > <span class="token variable">$*.asm</span>
    <span class="token variable">$</span><span class="token punctuation">(</span>OBJDUMP<span class="token punctuation">)</span> -t <span class="token variable">$@</span> <span class="token operator">|</span> sed <span class="token string">'1,/SYMBOL TABLE/d; s/ .* / /; /^$$/d'</span> > <span class="token variable">$*.sym</span>

<span class="token symbol">_forktest</span><span class="token punctuation">:</span> forktest.o <span class="token variable">$</span><span class="token punctuation">(</span>ULIB<span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true"># forktest has less library code linked in - needs to be small</span>
    <span class="token comment" spellcheck="true"># in order to be able to max out the proc table.</span>
    <span class="token variable">$</span><span class="token punctuation">(</span>LD<span class="token punctuation">)</span> <span class="token variable">$</span><span class="token punctuation">(</span>LDFLAGS<span class="token punctuation">)</span> -N -e main -Ttext 0 -o _forktest forktest.o ulib.o usys.o
    <span class="token variable">$</span><span class="token punctuation">(</span>OBJDUMP<span class="token punctuation">)</span> -S _forktest > forktest.asm

<span class="token symbol">mkfs</span><span class="token punctuation">:</span> mkfs.c fs.h
    gcc -Werror -Wall -o mkfs mkfs.c

<span class="token comment" spellcheck="true"># Prevent deletion of intermediate files, e.g. cat.o, after first build, so</span>
<span class="token comment" spellcheck="true"># that disk image changes after first build are persistent until clean.  More</span>
<span class="token comment" spellcheck="true"># details:</span>
<span class="token comment" spellcheck="true"># http://www.gnu.org/software/make/manual/html_node/Chained-Rules.html</span>
<span class="token builtin">.PRECIOUS</span><span class="token punctuation">:</span> %.o

UPROGS<span class="token operator">=</span>\
    _cat\
    _echo\
    _forktest\
    _grep\
    _init\
    _kill\
    _ln\
    _ls\
    _mkdir\
    _rm\
    _sh\
    _stressfs\
    _usertests\
    _wc\
    _zombie\

<span class="token symbol">fs.img</span><span class="token punctuation">:</span> mkfs README <span class="token variable">$</span><span class="token punctuation">(</span>UPROGS<span class="token punctuation">)</span>
    ./mkfs fs.img README <span class="token variable">$</span><span class="token punctuation">(</span>UPROGS<span class="token punctuation">)</span>

<span class="token keyword">-include</span> *.d

<span class="token symbol">clean</span><span class="token punctuation">:</span> 
    rm -f *.tex *.dvi *.idx *.aux *.log *.ind *.ilg \
    *.o *.d *.asm *.sym vectors.S bootblock entryother \
    initcode initcode.out kernel xv6.img fs.img kernelmemfs \
    xv6memfs.img mkfs .gdbinit \
    <span class="token variable">$</span><span class="token punctuation">(</span>UPROGS<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># make a printout</span>
FILES <span class="token operator">=</span> <span class="token variable">$</span><span class="token punctuation">(</span><span class="token keyword">shell</span> grep -v <span class="token string">'^\#'</span> runoff.list<span class="token punctuation">)</span>
PRINT <span class="token operator">=</span> runoff.list runoff.spec README toc.hdr toc.ftr <span class="token variable">$</span><span class="token punctuation">(</span>FILES<span class="token punctuation">)</span>

<span class="token symbol">xv6.pdf</span><span class="token punctuation">:</span> <span class="token variable">$</span><span class="token punctuation">(</span>PRINT<span class="token punctuation">)</span>
    ./runoff
    ls -l xv6.pdf

<span class="token symbol">print</span><span class="token punctuation">:</span> xv6.pdf

<span class="token comment" spellcheck="true"># run in emulators</span>

<span class="token symbol">bochs </span><span class="token punctuation">:</span> fs.img xv6.img
    if [ ! -e .bochsrc ]<span class="token punctuation">;</span> then ln -s dot-bochsrc .bochsrc<span class="token punctuation">;</span> fi
    bochs -q

<span class="token comment" spellcheck="true"># try to generate a unique GDB port</span>
GDBPORT <span class="token operator">=</span> <span class="token variable">$</span><span class="token punctuation">(</span><span class="token keyword">shell</span> expr `id -u` % 5000 + 25000<span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># QEMU's gdb stub command line changed in 0.11</span>
QEMUGDB <span class="token operator">=</span> <span class="token variable">$</span><span class="token punctuation">(</span><span class="token keyword">shell</span> if <span class="token variable">$</span><span class="token punctuation">(</span>QEMU<span class="token punctuation">)</span> -help <span class="token operator">|</span> grep -q <span class="token string">'^-gdb'</span><span class="token punctuation">;</span> \
    then echo <span class="token string">"-gdb tcp::$(GDBPORT)"</span><span class="token punctuation">;</span> \
    <span class="token keyword">else</span> echo <span class="token string">"-s -p $(GDBPORT)"</span><span class="token punctuation">;</span> fi<span class="token punctuation">)</span>
<span class="token keyword">ifndef</span> CPUS
CPUS <span class="token operator">:=</span> 2
<span class="token keyword">endif</span>
QEMUOPTS <span class="token operator">=</span> -drive file<span class="token operator">=</span>fs.img,index<span class="token operator">=</span>1,media<span class="token operator">=</span>disk,format<span class="token operator">=</span>raw -drive file<span class="token operator">=</span>xv6.img,index<span class="token operator">=</span>0,media<span class="token operator">=</span>disk,format<span class="token operator">=</span>raw -smp <span class="token variable">$</span><span class="token punctuation">(</span>CPUS<span class="token punctuation">)</span> -m 512 <span class="token variable">$</span><span class="token punctuation">(</span>QEMUEXTRA<span class="token punctuation">)</span>

<span class="token symbol">qemu</span><span class="token punctuation">:</span> fs.img xv6.img
<span class="token symbol">    <span class="token variable">$</span>(QEMU) -serial mon</span><span class="token punctuation">:</span>stdio <span class="token variable">$</span><span class="token punctuation">(</span>QEMUOPTS<span class="token punctuation">)</span>

<span class="token symbol">qemu-memfs</span><span class="token punctuation">:</span> xv6memfs.img
    <span class="token variable">$</span><span class="token punctuation">(</span>QEMU<span class="token punctuation">)</span> -drive file<span class="token operator">=</span>xv6memfs.img,index<span class="token operator">=</span>0,media<span class="token operator">=</span>disk,format<span class="token operator">=</span>raw -smp <span class="token variable">$</span><span class="token punctuation">(</span>CPUS<span class="token punctuation">)</span> -m 256

<span class="token symbol">qemu-nox</span><span class="token punctuation">:</span> fs.img xv6.img
    <span class="token variable">$</span><span class="token punctuation">(</span>QEMU<span class="token punctuation">)</span> -nographic <span class="token variable">$</span><span class="token punctuation">(</span>QEMUOPTS<span class="token punctuation">)</span>

<span class="token symbol">.gdbinit</span><span class="token punctuation">:</span> .gdbinit.tmpl
    sed <span class="token string">"s/localhost:1234/localhost:$(GDBPORT)/"</span> &lt; <span class="token variable">$^</span> > <span class="token variable">$@</span>

<span class="token symbol">qemu-gdb</span><span class="token punctuation">:</span> fs.img xv6.img .gdbinit
    <span class="token operator">@</span>echo <span class="token string">"*** Now run 'gdb'."</span> 1>&amp;2
<span class="token symbol">    <span class="token variable">$</span>(QEMU) -serial mon</span><span class="token punctuation">:</span>stdio <span class="token variable">$</span><span class="token punctuation">(</span>QEMUOPTS<span class="token punctuation">)</span> -S <span class="token variable">$</span><span class="token punctuation">(</span>QEMUGDB<span class="token punctuation">)</span>

<span class="token symbol">qemu-nox-gdb</span><span class="token punctuation">:</span> fs.img xv6.img .gdbinit
    <span class="token operator">@</span>echo <span class="token string">"*** Now run 'gdb'."</span> 1>&amp;2
    <span class="token variable">$</span><span class="token punctuation">(</span>QEMU<span class="token punctuation">)</span> -nographic <span class="token variable">$</span><span class="token punctuation">(</span>QEMUOPTS<span class="token punctuation">)</span> -S <span class="token variable">$</span><span class="token punctuation">(</span>QEMUGDB<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># CUT HERE</span>
<span class="token comment" spellcheck="true"># prepare dist for students</span>
<span class="token comment" spellcheck="true"># after running make dist, probably want to</span>
<span class="token comment" spellcheck="true"># rename it to rev0 or rev1 or so on and then</span>
<span class="token comment" spellcheck="true"># check in that version.</span>

EXTRA<span class="token operator">=</span>\
    mkfs.c ulib.c user.h cat.c echo.c forktest.c grep.c kill.c\
    ln.c ls.c mkdir.c rm.c stressfs.c usertests.c wc.c zombie.c\
    printf.c umalloc.c\
    README dot-bochsrc *.pl toc.* runoff runoff1 runoff.list\
    .gdbinit.tmpl gdbutil\

<span class="token symbol">dist</span><span class="token punctuation">:</span>
    rm -rf dist
    mkdir dist
    for i in <span class="token variable">$</span><span class="token punctuation">(</span>FILES<span class="token punctuation">)</span><span class="token punctuation">;</span> \
    do \
        grep -v PAGEBREAK <span class="token variable">$$i</span> >dist/<span class="token variable">$$i;</span> \
    done
    sed <span class="token string">'/CUT HERE/,$$d'</span> Makefile >dist/Makefile
    echo >dist/runoff.spec
    cp <span class="token variable">$</span><span class="token punctuation">(</span>EXTRA<span class="token punctuation">)</span> dist

<span class="token symbol">dist-test</span><span class="token punctuation">:</span>
    rm -rf dist
    make dist
    rm -rf dist-test
    mkdir dist-test
    cp dist/* dist-test
    cd dist-test<span class="token punctuation">;</span> <span class="token variable">$</span><span class="token punctuation">(</span>MAKE<span class="token punctuation">)</span> print
    cd dist-test<span class="token punctuation">;</span> <span class="token variable">$</span><span class="token punctuation">(</span>MAKE<span class="token punctuation">)</span> bochs <span class="token operator">|</span><span class="token operator">|</span> true
    cd dist-test<span class="token punctuation">;</span> <span class="token variable">$</span><span class="token punctuation">(</span>MAKE<span class="token punctuation">)</span> qemu

<span class="token comment" spellcheck="true"># update this rule (change rev#) when it is time to</span>
<span class="token comment" spellcheck="true"># make a new revision.</span>
<span class="token symbol">tar</span><span class="token punctuation">:</span>
    rm -rf /tmp/xv6
    mkdir -p /tmp/xv6
    cp dist/* dist/.gdbinit.tmpl /tmp/xv6
    <span class="token punctuation">(</span>cd /tmp<span class="token punctuation">;</span> tar cf - xv6<span class="token punctuation">)</span> <span class="token operator">|</span> gzip >xv6-rev10.tar.gz  <span class="token comment" spellcheck="true"># the next one will be 10 (9/17)</span>

<span class="token builtin">.PHONY</span><span class="token punctuation">:</span> dist-test dist
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="A-调试XV6-make-qemu-nox-gdb"><a href="#A-调试XV6-make-qemu-nox-gdb" class="headerlink" title="A. 调试XV6: make qemu-nox-gdb"></a>A. 调试XV6: <code>make qemu-nox-gdb</code></h3><p>为了调试<code>XV6</code>，我们在命令行中使用的命令是</p>
<pre class="line-numbers language-bash"><code class="language-bash"><span class="token function">make</span> qemu-nox-gdb
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>而这个命令表示我们运行<code>Makefile</code>中的 <code>qemu-nox-gdb</code>目标。</p>
<p><code>Makefile</code>中的 <code>qemu-nox-gdb</code>目标如下：</p>
<pre class="line-numbers language-makefile"><code class="language-makefile"><span class="token symbol">qemu-nox-gdb</span><span class="token punctuation">:</span> fs.img xv6.img .gdbinit
    <span class="token operator">@</span>echo <span class="token string">"*** Now run 'gdb'."</span> 1>&amp;2
    <span class="token variable">$</span><span class="token punctuation">(</span>QEMU<span class="token punctuation">)</span> -nographic <span class="token variable">$</span><span class="token punctuation">(</span>QEMUOPTS<span class="token punctuation">)</span> -S <span class="token variable">$</span><span class="token punctuation">(</span>QEMUGDB<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>其中：</p>
<ul>
<li><code>@echo</code>是输出命令</li>
<li><code>QEMU</code>、<code>QEMUOPTS</code>和<code>QEMUGDB</code>三个都是宏</li>
<li><code>qemu-nox-gdb: fs.img xv6.img .gdbinit</code>表示目标<code>qemu-nox-gdb</code>依赖目标<code>fs.img</code>, <code>xv6.img</code>和 <code>.gdbinit</code>，即在build目标<code>qemu-nox-gdb</code>之前，要先build后面三个目标</li>
</ul>
<p>宏 <code>QEMU</code>, <code>QEMUOPTS</code>和 <code>QEMUGDB</code>的定义为</p>
<pre class="line-numbers language-makefile"><code class="language-makefile">QEMU <span class="token operator">=</span> <span class="token variable">$</span><span class="token punctuation">(</span><span class="token keyword">shell</span> if which qemu > /dev/null<span class="token punctuation">;</span> \
    then echo qemu<span class="token punctuation">;</span> exit<span class="token punctuation">;</span> \
    elif which qemu-system-i386 > /dev/null<span class="token punctuation">;</span> \
    then echo qemu-system-i386<span class="token punctuation">;</span> exit<span class="token punctuation">;</span> \
    elif which qemu-system-x86_64 > /dev/null<span class="token punctuation">;</span> \
    then echo qemu-system-x86_64<span class="token punctuation">;</span> exit<span class="token punctuation">;</span> \
    <span class="token keyword">else</span> \
    qemu<span class="token operator">=</span>/Applications/Q.app/Contents/MacOS/i386-softmmu.app/Contents/MacOS/i386-softmmu<span class="token punctuation">;</span> \
    if test -x <span class="token variable">$$qemu;</span> then echo <span class="token variable">$$qemu;</span> exit<span class="token punctuation">;</span> fi<span class="token punctuation">;</span> fi<span class="token punctuation">;</span> \
    echo <span class="token string">"***"</span> 1>&amp;2<span class="token punctuation">;</span> \
    echo <span class="token string">"*** Error: Couldn't find a working QEMU executable."</span> 1>&amp;2<span class="token punctuation">;</span> \
    echo <span class="token string">"*** Is the directory containing the qemu binary in your PATH"</span> 1>&amp;2<span class="token punctuation">;</span> \
    echo <span class="token string">"*** or have you tried setting the QEMU variable in Makefile?"</span> 1>&amp;2<span class="token punctuation">;</span> \
    echo <span class="token string">"***"</span> 1>&amp;2<span class="token punctuation">;</span> exit 1<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-makefile"><code class="language-makefile">QEMUOPTS <span class="token operator">=</span> -drive file<span class="token operator">=</span>fs.img,index<span class="token operator">=</span>1,media<span class="token operator">=</span>disk,format<span class="token operator">=</span>raw -drive file<span class="token operator">=</span>xv6.img,index<span class="token operator">=</span>0,media<span class="token operator">=</span>disk,format<span class="token operator">=</span>raw -smp <span class="token variable">$</span><span class="token punctuation">(</span>CPUS<span class="token punctuation">)</span> -m 512 <span class="token variable">$</span><span class="token punctuation">(</span>QEMUEXTRA<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<pre class="line-numbers language-makefile"><code class="language-makefile">QEMUGDB <span class="token operator">=</span> <span class="token variable">$</span><span class="token punctuation">(</span><span class="token keyword">shell</span> if <span class="token variable">$</span><span class="token punctuation">(</span>QEMU<span class="token punctuation">)</span> -help <span class="token operator">|</span> grep -q <span class="token string">'^-gdb'</span><span class="token punctuation">;</span> \
    then echo <span class="token string">"-gdb tcp::$(GDBPORT)"</span><span class="token punctuation">;</span> \
    <span class="token keyword">else</span> echo <span class="token string">"-s -p $(GDBPORT)"</span><span class="token punctuation">;</span> fi<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>所以<code>QEMU</code>这个宏就是就是循找系统上当前可用的<code>qemu</code>版本，而<code>QEMUOPTS</code>定义了一系列运行<code>qemu</code>时候的命令行参数，而<code>QEMUGDB</code>宏就是指定用<code>gdb</code>进行调试，同时指定<code>gdbserver</code>的端口</p>
<p><strong>此外，需要注意的是，在宏<code>QEMUOPTS</code>中，<code>-drive</code>选项后面定义了运行虚拟机时候使用了两个硬盘镜像：<code>fs.img</code>和<code>xv6.img</code>。换而言之，<code>-drive</code>选项说了我们的系统是安装在<code>fs.img</code>和<code>xv6.img</code>这两个硬盘镜像上的。</strong></p>
<h3 id="B-xv6-img"><a href="#B-xv6-img" class="headerlink" title="B. xv6.img"></a>B. <code>xv6.img</code></h3><p>接下来向上追溯，看看<code>xv6.img</code>这个target：</p>
<pre class="line-numbers language-makefile"><code class="language-makefile"><span class="token symbol">xv6.img</span><span class="token punctuation">:</span> bootblock kernel
    dd if<span class="token operator">=</span>/dev/zero of<span class="token operator">=</span>xv6.img count<span class="token operator">=</span>10000
    dd if<span class="token operator">=</span>bootblock of<span class="token operator">=</span>xv6.img conv<span class="token operator">=</span>notrunc
    dd if<span class="token operator">=</span>kernel of<span class="token operator">=</span>xv6.img seek<span class="token operator">=</span>1 conv<span class="token operator">=</span>notrunc
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p><code>xv6.img</code>这个目标首先创建了一个空的磁盘映像<code>xv6.img</code>，然后把<code>bootblock</code>写入到了磁盘的第零个块，而后把<code>kernel</code>写入到第一个块。</p>
<p>此外，<code>xv6.img</code>目标依赖于<code>bootblock</code>和<code>kernel</code>这两个目标。</p>
<h3 id="C-kernel"><a href="#C-kernel" class="headerlink" title="C. kernel"></a>C. <code>kernel</code></h3><p><code>xv6.img</code>目标依赖了<code>bootblock</code>和<code>kernel</code>这两个目标，所以我们接下来先看看<code>kernel</code>这个目标</p>
<pre class="line-numbers language-makefile"><code class="language-makefile"><span class="token symbol">kernel</span><span class="token punctuation">:</span> <span class="token variable">$</span><span class="token punctuation">(</span>OBJS<span class="token punctuation">)</span> entry.o entryother initcode kernel.ld
    <span class="token variable">$</span><span class="token punctuation">(</span>LD<span class="token punctuation">)</span> <span class="token variable">$</span><span class="token punctuation">(</span>LDFLAGS<span class="token punctuation">)</span> -T kernel.ld -o kernel entry.o <span class="token variable">$</span><span class="token punctuation">(</span>OBJS<span class="token punctuation">)</span> -b binary initcode entryother
    <span class="token variable">$</span><span class="token punctuation">(</span>OBJDUMP<span class="token punctuation">)</span> -S kernel > kernel.asm
    <span class="token variable">$</span><span class="token punctuation">(</span>OBJDUMP<span class="token punctuation">)</span> -t kernel <span class="token operator">|</span> sed <span class="token string">'1,/SYMBOL TABLE/d; s/ .* / /; /^$$/d'</span> > kernel.sym
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>看这个样子，<code>kernel</code>这个目标干的事情就是把目标<code>entry.o</code>、<code>entryother</code>等等编译出来的目标文件（<code>.o</code>）连接在一起，最终输出<code>kernel</code>这个可执行文件。</p>
<p>而后通过<code>objdump</code>这个命令（在宏<code>OBJDUMP</code>中定义）把<code>kernel</code>反汇编出来，并且把其中的的符号全部列出来。</p>
<h3 id="D-bootblock"><a href="#D-bootblock" class="headerlink" title="D. bootblock"></a>D. <code>bootblock</code></h3><p>接下来看看<code>bootblock</code>这个目标，<code>bootblock</code>这个目标内容如下</p>
<pre class="line-numbers language-makefile"><code class="language-makefile"><span class="token symbol">bootblock</span><span class="token punctuation">:</span> bootasm.S bootmain.c
    <span class="token variable">$</span><span class="token punctuation">(</span>CC<span class="token punctuation">)</span> <span class="token variable">$</span><span class="token punctuation">(</span>CFLAGS<span class="token punctuation">)</span> -fno-pic -O -nostdinc -I. -c bootmain.c
    <span class="token variable">$</span><span class="token punctuation">(</span>CC<span class="token punctuation">)</span> <span class="token variable">$</span><span class="token punctuation">(</span>CFLAGS<span class="token punctuation">)</span> -fno-pic -nostdinc -I. -c bootasm.S
    <span class="token variable">$</span><span class="token punctuation">(</span>LD<span class="token punctuation">)</span> <span class="token variable">$</span><span class="token punctuation">(</span>LDFLAGS<span class="token punctuation">)</span> -N -e start -Ttext 0x7C00 -o bootblock.o bootasm.o bootmain.o
    <span class="token variable">$</span><span class="token punctuation">(</span>OBJDUMP<span class="token punctuation">)</span> -S bootblock.o > bootblock.asm
    <span class="token variable">$</span><span class="token punctuation">(</span>OBJCOPY<span class="token punctuation">)</span> -S -O binary -j .text bootblock.o bootblock
    ./sign.pl bootblock
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>具体来说，<code>bootblock</code>目标干的事情就是编译了<code>bootmain.c</code>和<code>bootasm.S</code>这两个程序，然后把它们连接在一起之后生成<code>bootblock.o</code></p>
<p>接下来通过<code>objdump</code>和<code>objcopy</code>来分别进行反汇编和代码段拷贝。</p>
<p>最后运行<code>sign.pl</code>脚本来进行处理。</p>
<h3 id="E-fs-img"><a href="#E-fs-img" class="headerlink" title="E. fs.img"></a>E. <code>fs.img</code></h3><p>介绍完了<code>xv6.img</code>接下来我们介绍<code>fs.img</code></p>
<pre class="line-numbers language-makefile"><code class="language-makefile">UPROGS<span class="token operator">=</span>\
    _cat\
    _echo\
    _forktest\
    _grep\
    _init\
    _kill\
    _ln\
    _ls\
    _mkdir\
    _rm\
    _sh\
    _stressfs\
    _usertests\
    _wc\
    _zombie\

<span class="token symbol">fs.img</span><span class="token punctuation">:</span> mkfs README <span class="token variable">$</span><span class="token punctuation">(</span>UPROGS<span class="token punctuation">)</span>
    ./mkfs fs.img README <span class="token variable">$</span><span class="token punctuation">(</span>UPROGS<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><code>fs.img</code>这个目标主要就是通过<code>mkfs</code>这个程序来向<code>fs.img</code>中写入宏<code>UPROGS</code>中指明的程序。</p>
<h3 id="F-总结"><a href="#F-总结" class="headerlink" title="F. 总结"></a>F. 总结</h3><p>总结一下，当我们在命令行中运行<code>make qemu-nox-gdb</code>命令的时候，<code>make</code>在背后默默为我们做了下面这些事：</p>
<ol>
<li>编译内核，并将得到的<code>kernel</code>程序写入到<code>xv6.img</code>这个磁盘映像文件中。</li>
<li>编译用户程序，而后将所有的用户程序写入到<code>fs.img</code>中</li>
<li>将<code>xv6.img</code>和<code>fs.img</code>作为虚拟机的磁盘，通过<code>qemu</code>启动虚拟机</li>
<li>使用<code>qemu</code>的时候启动<code>gdb server</code>以支持远程调试</li>
</ol>
<p>到现在为止，我们已经介绍了<code>XV6</code>项目的历史渊源，并且介绍了<code>XV6</code>的项目结构</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Jack Wang</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://jackwang0107.github.io/2022/10/22/xv6-xiang-mu-jie-shao/">https://jackwang0107.github.io/2022/10/22/xv6-xiang-mu-jie-shao/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Jack Wang</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Operating-System/">
                                    <span class="chip bg-color">Operating System</span>
                                </a>
                            
                                <a href="/tags/xv6/">
                                    <span class="chip bg-color">xv6</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.jpg" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2022/10/22/xv6-zeng-jia-xi-tong-diao-yong/">
                    <div class="card-image">
                        
                        <img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20221022160403946.png" class="responsive-img" alt="XV6：增加系统调用">
                        
                        <span class="card-title">XV6：增加系统调用</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本文介绍了如何为XV6增加系统调用
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2022-10-22
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/xv6/" class="post-category">
                                    xv6
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Operating-System/">
                        <span class="chip bg-color">Operating System</span>
                    </a>
                    
                    <a href="/tags/xv6/">
                        <span class="chip bg-color">xv6</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2022/10/17/gams-jiao-cheng-8-zui-xiao-fei-yong-liu-wen-ti/">
                    <div class="card-image">
                        
                        <img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20221017221456195.png" class="responsive-img" alt="GAMS教程 8：最小费用流问题">
                        
                        <span class="card-title">GAMS教程 8：最小费用流问题</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本文介绍了GAMS如何解决最小费用流问题
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2022-10-17
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/GAMS/" class="post-category">
                                    GAMS
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/GAMS/">
                        <span class="chip bg-color">GAMS</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE' || selection.getRangeAt(0).commonAncestorContainer.nodeName === 'CODE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: JackWang&#39;s Blog<br />'
            + '文章作者: Jack Wang<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('2'),
            headingSelector: 'h1, h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    

    <div class="container row center-align"
         style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2021-2023</span>
            
            <a href="/about" target="_blank">Jack Wang</a>
            <!-- |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a> -->
            <!-- |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a> -->
            <br>
            
                &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                        class="white-color">603.8k</span>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
                <span id="sitetime"> Loading ...</span>
                <script>
                    var calcSiteTime = function () {
                        var seconds = 1000;
                        var minutes = seconds * 60;
                        var hours = minutes * 60;
                        var days = hours * 24;
                        var years = days * 365;
                        var today = new Date();
                        var startYear = "2021";
                        var startMonth = "11";
                        var startDate = "12";
                        var startHour = "0";
                        var startMinute = "0";
                        var startSecond = "0";
                        var todayYear = today.getFullYear();
                        var todayMonth = today.getMonth() + 1;
                        var todayDate = today.getDate();
                        var todayHour = today.getHours();
                        var todayMinute = today.getMinutes();
                        var todaySecond = today.getSeconds();
                        var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                        var diff = t2 - t1;
                        var diffYears = Math.floor(diff / years);
                        var diffDays = Math.floor((diff / days) - diffYears * 365);

                        // 区分是否有年份.
                        var language = 'zh-CN';
                        if (startYear === String(todayYear)) {
                            document.getElementById("year").innerHTML = todayYear;
                            var daysTip = 'This site has been running for ' + diffDays + ' days';
                            if (language === 'zh-CN') {
                                daysTip = '本站已运行 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                daysTip = '本站已運行 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = daysTip;
                        } else {
                            document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                            var yearsAndDaysTip = 'This site has been running for ' + diffYears + ' years and '
                                + diffDays + ' days';
                            if (language === 'zh-CN') {
                                yearsAndDaysTip = '本站已运行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                yearsAndDaysTip = '本站已運行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = yearsAndDaysTip;
                        }
                    }

                    calcSiteTime();
                </script>
            
            <br>
            
                <span id="icp"><img src="/medias/icp.png"
                                    style="vertical-align: text-bottom;"/>
                <a href="https://beian.miit.gov.cn" target="_blank">陕ICP备2021014294号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/jackwang0108" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:2232123545@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2232123545" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2232123545" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    

    
        
        <script type="text/javascript">
            // 只在桌面版网页启用特效
            var windowWidth = $(window).width();
            if (windowWidth > 768) {
                document.write('<script type="text/javascript" src="/libs/others/sakura.js"><\/script>');
            }
        </script>
    

    <!-- 雪花特效 -->
    

    <!-- 鼠标星星特效 -->
    

     
        <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
        <script src="/libs/others/TencentCaptcha.js"></script>
        <button id="TencentCaptcha" data-appid="xxxxxxxxxx" data-cbfn="callback" type="button" hidden></button>
    

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
